using System;
using System.Collections.Generic;
using LitJson;

namespace abilities.targets
{
    public class TargetsAround : Target
    {
        public TargetUnitSide unitSide;
        public TargetUnitType unitType;
        public float radius;
        public float minRadius;
        public bool includeSelf;

        public TargetsAround()
        {
            unitSide = TargetUnitSide.ENEMY;
            radius = 0;
            minRadius = 0;
            unitType = 0;
            includeSelf = false;
        }


        public TargetsAround(TargetUnitSide unitSide, float radius, float minRadius, TargetUnitType unitType, bool includeSelf)
        {
            this.unitSide = unitSide;
            this.radius = radius;
            this.minRadius = minRadius;
            this.unitType = unitType;
            this.includeSelf = includeSelf;
        }

        public override bool FromJson(JsonData value)
        {
            string battleSide = (string)value["unitSide"];
            if ("ENEMY" == battleSide)
            {
                unitSide = TargetUnitSide.ENEMY;
            }
            else
            {
                unitSide = TargetUnitSide.ALLY;
            }

            radius = (int)value["radius"] / 100.0f;
            minRadius = (int)value["minRadius"] / 100.0f;
            unitType = Enum.Parse<TargetUnitType>((string)value["unitType"]);
            includeSelf = (bool)value["includeSelf"];
            return true;
        }

        public override List<TargetObject> GetTargets(AbilityContext context)
        {
            List<TargetObject> result = new List<TargetObject>();
            List<UnitObject> units = UnitObject.UnitsInSight();
            if (units.Count <1)
                return result;

            UnitObject owner = (UnitObject) (context.AbilityManager.Owner);
            TargetUnitType usingTargetUnitType = unitType != null ? unitType : 0;

            foreach (var it in units)
            {
                if (!includeSelf && owner == (it))
                {
                    continue;
                }

                if (it.isDead())
                {
                    continue;
                }

                if (unitSide == TargetUnitSide.ENEMY &&
                    owner == it)
                {
                    continue;
                }

                if (unitSide == TargetUnitSide.ALLY &&
                    owner != it)
                {
                    continue;
                }
  
                result.Add(new TargetObject(it));
            }
            return result;
        }
    }
}